<template>
  <div class="daily-record-container">
    <!-- 筛选 -->
    <a-form class="form" layout="inline">
      <a-form-item label="日期">
        <a-month-picker :allowClear="false" format="YYYY-MM" v-model="year_month" @change="handleChangeMonth" />
      </a-form-item>
    </a-form>
    <!-- 表格 -->
    <vxe-table border resizable keep-source show-overflow ref="xTable" :data="tableData" :row-config="{'height':230}"
      :loading="loading">
      <vxe-column width="120" field="vehicle_number" title="车牌号" fixed="left"></vxe-column>
      <vxe-column v-for="item in tableColumns" :key="item.date" :field="item.date" :title="item.date" min-width="180">
        <template #header="{ column }">
          <span :style="['星期六','星期日'].includes(item.weekday) ? { color:'red' } : {}">
            {{item.date}}
          </span>
        </template>
        <template #default="{ row }">
          <div v-if="row[item.date].recorder_id">
            <span style="margin-left:28px"></span><br>
            <span style="margin-left:28px">记录人：{{row[item.date].recorder_name}}</span><br>
            <span style="margin-left:14px">开始里程：{{row[item.date].start_km}} KM</span><br>
            <span style="margin-left:14px">结束里程：{{row[item.date].end_km}} KM</span><br>
            <span style="margin-left:28px">燃油费：￥{{row[item.date].fuel_cost.toFixed(2)}}</span><br>
            <span style="margin-left:28px">充电费：￥{{row[item.date].charge_cost.toFixed(2)}}</span><br>
            <span>维修保养费：￥{{row[item.date].repair_cost.toFixed(2)}}</span><br>
            <span>过路过桥费：￥{{row[item.date].roads_cost.toFixed(2)}}</span><br>
            <span style="margin-left:14px">其他费用：￥{{row[item.date].other_cost.toFixed(2)}}</span><br>
            <span style="margin-left:42px">备注：{{row[item.date].remark}}</span><br>
          </div>
          <!-- 编辑 -->
          <a-button v-if="row[item.date].recorder_id" style="position:absolute;top:4px;left:4px;" size="small"
            type="dashed" shape="circle" icon="edit" @click="handleOpenDrawer({type:'edit',row,date:item.date})" />
          <!-- 新增 -->
          <a-button v-else style="position:absolute;top:4px;left:4px;" size="small" type="dashed" shape="circle"
            icon="plus" @click="handleOpenDrawer({type:'add',row,date:item.date})" />
          <!-- 删除 -->
          <a-popconfirm v-if="row[item.date].recorder_id" title="确认要删除吗？" ok-text="是" cancel-text="否"
            @confirm="handleDel({row,date:item.date})">
            <a-button style="position:absolute;top:4px;right:4px;" size="small" type="danger" shape="circle"
              icon="delete" />
          </a-popconfirm>
        </template>
      </vxe-column>
    </vxe-table>
    <!-- 编辑抽屉 -->
    <a-drawer :title="drawerType === 'add' ? '新增' : '编辑'" :width="720" :visible="drawerVisible"
      :body-style="{ paddingBottom: '80px' }" @close="drawerVisible = false">
      <!-- 新增表单 -->
      <a-form v-if="drawerType === 'add'" :form="drawerForm" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }">
        <a-form-model-item label="车牌号" prop="vehicle_number">
          <span>{{ drawerForm.vehicle_number }}</span>
        </a-form-model-item>
        <a-form-model-item label="日期" prop="record_date">
          <span>{{ drawerForm.record_date }}</span>
        </a-form-model-item>
        <a-form-model-item label="记录人" prop="recorder_id">
          <span>{{ personInfo.person_name }}</span>
        </a-form-model-item>
        <a-form-model-item label="开始里程" prop="start_km">
          <a-input-number style="width:160px;" v-model="drawerForm.start_km" :min="0" /> KM
        </a-form-model-item>
        <a-form-model-item label="结束里程" prop="end_km">
          <a-input-number style="width:160px;" v-model="drawerForm.end_km" :min="0" /> KM
        </a-form-model-item>
        <a-form-model-item label="燃油费" prop="fuel_cost">
          <a-input-number style="width:160px;" v-model="drawerForm.fuel_cost" :min="0" :step="0.01" />
        </a-form-model-item>
        <a-form-model-item label="充电费" prop="charge_cost">
          <a-input-number style="width:160px;" v-model="drawerForm.charge_cost" :min="0" :step="0.01" />
        </a-form-model-item>
        <a-form-model-item label="维修保养费" prop="repair_cost">
          <a-input-number style="width:160px;" v-model="drawerForm.repair_cost" :min="0" :step="0.01" />
        </a-form-model-item>
        <a-form-model-item label="过路过桥费" prop="roads_cost">
          <a-input-number style="width:160px;" v-model="drawerForm.roads_cost" :min="0" :step="0.01" />
        </a-form-model-item>
        <a-form-model-item label="其他费用" prop="other_cost">
          <a-input-number style="width:160px;" v-model="drawerForm.other_cost" :min="0" :step="0.01" />
        </a-form-model-item>
        <a-form-model-item label="备注" prop="remark">
          <a-textarea v-model="drawerForm.remark" placeholder="请输入备注" :auto-size="{ minRows: 3, maxRows: 5 }" />
        </a-form-model-item>
        <a-form-model-item>
          <a-button type="primary" :loading="drawerLaoding" @click="handleAdd()" style="float:right;">
            新增提交
          </a-button>
        </a-form-model-item>
      </a-form>
      <!-- 编辑表单 -->
      <a-form v-if="drawerType === 'edit'" :form="drawerForm" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }">
        <a-form-model-item label="车牌号" prop="vehicle_number">
          <span>{{ drawerForm.vehicle_number }}</span>
        </a-form-model-item>
        <a-form-model-item label="日期" prop="record_date">
          <span>{{ drawerForm.record_date }}</span>
        </a-form-model-item>
        <a-form-model-item label="记录人" prop="recorder_id">
          <span>{{ personInfo.person_name }}</span>
        </a-form-model-item>
        <a-form-model-item label="开始里程" prop="start_km">
          <a-input-number style="width:160px;" v-model="drawerForm.start_km" :min="0" /> KM
        </a-form-model-item>
        <a-form-model-item label="结束里程" prop="end_km">
          <a-input-number style="width:160px;" v-model="drawerForm.end_km" :min="0" /> KM
        </a-form-model-item>
        <a-form-model-item label="燃油费" prop="fuel_cost">
          <a-input-number style="width:160px;" v-model="drawerForm.fuel_cost" :min="0" :step="0.01" />
        </a-form-model-item>
        <a-form-model-item label="充电费" prop="charge_cost">
          <a-input-number style="width:160px;" v-model="drawerForm.charge_cost" :min="0" :step="0.01" />
        </a-form-model-item>
        <a-form-model-item label="维修保养费" prop="repair_cost">
          <a-input-number style="width:160px;" v-model="drawerForm.repair_cost" :min="0" :step="0.01" />
        </a-form-model-item>
        <a-form-model-item label="过路过桥费" prop="roads_cost">
          <a-input-number style="width:160px;" v-model="drawerForm.roads_cost" :min="0" :step="0.01" />
        </a-form-model-item>
        <a-form-model-item label="其他费用" prop="other_cost">
          <a-input-number style="width:160px;" v-model="drawerForm.other_cost" :min="0" :step="0.01" />
        </a-form-model-item>
        <a-form-model-item label="备注" prop="remark">
          <a-textarea v-model="drawerForm.remark" placeholder="请输入备注" :auto-size="{ minRows: 3, maxRows: 5 }" />
        </a-form-model-item>
        <a-form-model-item>
          <a-button type="primary" :loading="drawerLaoding" @click="handleEdit()" style="float:right;">
            编辑提交
          </a-button>
        </a-form-model-item>
      </a-form>
    </a-drawer>
  </div>
</template>
<script>
  import {
    apiVehicleApplicationDailyRecords,
    apiCreateVehicleDailyRecord,
    apiUpdateVehicleDailyRecord,
    apiDeleteVehicleDailyRecord
  } from '@/api/featch'

  import moment from 'moment'

  const personInfo = JSON.parse(window.sessionStorage.getItem('person_info') || '{}')

  export default {
    name: 'DailyRecord',
    data() {
      return {
        personInfo,
        year_month: moment(),
        year_month_format: moment().format('YYYY-MM'),
        loading: false,
        tableHeight: 0,
        tableData: [],
        tableColumns: [],

        // 抽屉
        drawerType: 'add', // add || edit
        drawerForm: {},
        drawerLaoding: false,
        drawerVisible: false

      }
    },
    computed: {

    },
    mounted() {
      this.initTableHeight()
      window.addEventListener('resize', this.initTableHeight)
      this.handleGetInit()
    },
    methods: {
      initTableHeight() {
        const clientHeight = document.documentElement.clientHeight
        this.tableHeight = clientHeight - 40 - 32
      },
      handleGetInit() {
        this.loading = true
        // 这个月的每一天
        this.tableColumns = this.getDaysInMonth(this.year_month_format)

        // 正则表达式用于匹配 YYYY-MM-DD 格式
        const regex = /^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$/;

        // 获取数据
        apiVehicleApplicationDailyRecords({
          year_month: this.year_month_format,
        }).then(res => {
          this.loading = false
          this.tableData = res.data
          res.data.map(item => {
            Object.keys(item).forEach(key => {
              if (regex.test(key)) {
                item[key] = JSON.parse(item[key])
              }
            })
          })
        }).catch(err => {
          this.loading = false
        })
      },
      getDaysInMonth(dateStr) {
        const daysArray = [];
        const startOfMonth = moment(dateStr, 'YYYY-MM');
        const endOfMonth = startOfMonth.clone().endOf('month');
        let currentDate = startOfMonth.clone();
        while (currentDate <= endOfMonth) {
          const dayObj = {
            date: currentDate.format('YYYY-MM-DD'),
            weekday: currentDate.format('dddd')
          };
          daysArray.push(dayObj);
          currentDate = currentDate.add(1, 'day');
        }
        return daysArray;
      },
      /** 日期选择器组件 改变回调 */
      handleChangeMonth() {
        this.year_month_format = this.year_month.format('YYYY-MM')
        this.handleGetInit()
      },
      // 跳转日历页面
      handleRouteToCalendarView(row) {
        // const routeTarget = this.$router.resolve({
        //   name: 'calendarview',
        //   query: {
        //     person_id: row.person_id,
        //     person_name: row.person_name
        //   }
        // })
        // window.open(routeTarget.href, '_blank')
      },
      // 打开抽屉
      handleOpenDrawer({
        type,
        row,
        date
      }) {
        this.drawerType = type
        if (type === 'add') {
          this.drawerVisible = true
          this.drawerForm = {
            vehicle_number: row.vehicle_number,
            vehicle_id: row.vehicle_id,
            recorder_id: personInfo.person_id,
            record_date: date,
            start_km: 0,
            end_km: 0,
            fuel_cost: 0,
            charge_cost: 0,
            repair_cost: 0,
            roads_cost: 0,
            other_cost: 0,
            remark: null
          }
        } else if (type === 'edit') {
          this.drawerVisible = true
          this.drawerForm = {
            record_id: row[date].record_id,
            vehicle_number: row.vehicle_number,
            vehicle_id: row.vehicle_id,
            recorder_id: personInfo.person_id,
            record_date: date,
            start_km: row[date].start_km,
            end_km: row[date].end_km,
            fuel_cost: row[date].fuel_cost,
            charge_cost: row[date].charge_cost,
            repair_cost: row[date].repair_cost,
            roads_cost: row[date].roads_cost,
            other_cost: row[date].other_cost,
            remark: row[date].remark
          }
        }

      },
      /**
       * @description 确认新增
       */
      handleAdd() {
        this.drawerLaoding = true
        apiCreateVehicleDailyRecord(this.drawerForm)
          .then(res => {
            this.drawerLaoding = false
            if (res.code === 200) {
              this.$message.success('提交成功')
              this.drawerVisible = false
              this.handleGetInit()
            } else {
              this.$message.error(res.message)
            }
          })
          .catch(err => {
            this.drawerLaoding = false
          })
      },
      /**
       * @description 确认编辑
       */
      handleEdit() {
        this.drawerLaoding = true
        apiUpdateVehicleDailyRecord(this.drawerForm)
          .then(res => {
            this.drawerLaoding = false
            if (res.code === 200) {
              this.$message.success('编辑成功')
              this.drawerVisible = false
              this.handleGetInit()
            } else {
              this.$message.error(res.message)
            }
          })
          .catch(err => {
            this.drawerLaoding = false
          })
      },
      /**
       * @description 确认删除
       */
      handleDel({
        date,
        row
      }) {
        console.log(date)
        console.log(row[date])
        this.loading = true
        apiDeleteVehicleDailyRecord({
            record_id: row[date].record_id
          }).then(res => {
            this.loading = false
            if (res.code === 200) {
              this.$message.success('删除成功')
              this.handleGetInit()
            } else {
              this.$message.error(res.message)
            }
          })
          .catch(err => {
            this.loading = false
          })
      }
    },
  };
</script>

<style lang="less" scoped>
  .daily-record-container {
    // height: calc(100vh - 32px);
    overflow-y: hidden;

    .form {
      margin-bottom: 0
    }

    ::-webkit-scrollbar {
      width: 12px;
      height: 12px;
      /*background-color: #ddd;*/
    }


    /*滑块*/
    ::-webkit-scrollbar-thumb {
      background-color: rgba(83, 166, 255, 0.5);
      border-radius: 8px;
    }

    ::-webkit-scrollbar-thumb:hover {
      background-color: #777;
    }


    /*滑道*/
    ::-webkit-scrollbar-track {
      /* box-shadow: inset 0 0 6px #333; */
      border-radius: 8px;
    }

  }
</style>